package code.example.zookeeper.zk;

import code.example.zookeeper.ZkConstant;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.util.concurrent.locks.LockSupport;

import static code.example.zookeeper.ZkConstant.connectString;

public class ConnectTest {


    ZooKeeper zooKeeper = null;
    volatile  boolean connected = false;
      boolean init = false;
      private String connectString = ZkConstant.connectString;

    public String getConnectString() {
        return connectString;
    }

    public void setConnectString(String connectString) {
        this.connectString = connectString;
    }

    public ConnectTest(String connectString,StringBuffer sb){
        this.watcherTest = new WatcherTest(this) ;
    }
    WatcherTest watcherTest = null;
    private   void  connect() throws Exception {
        ZooKeeper zooKeeperClient = new ZooKeeper(this.connectString, 3000,  this.watcherTest);
        this.zooKeeper = zooKeeperClient;
        this.init = true;
    }

    public ZooKeeper  getZooKeeper() throws Exception{
        if(connected ){
            return this.zooKeeper;
        }else{
            synchronized (this){
                if(!init){
                    connect();
                }
                while(!connected){
                    this.wait();
                }
            }
            return this.zooKeeper;
        }
    }
     void notifyAvailable(boolean flag){
        if(!this.connected && flag){
            synchronized (this){
                this.notifyAll();
            }
        }
        this.connected = flag;
    }
}
